import 'package:dio/dio.dart';
import 'package:flutter_app/base/net/base_request.dart';
import 'package:flutter_app/base/net/hi_error.dart';
import 'package:flutter_app/base/net/lp_net_adapter.dart';

class DioAdapter extends LpNetAdapter {
  @override
  Future<BaseResponse> send<T>(BaseRequest request) async {
    Response? response;
    var option = Options(headers: request.header);
    var error;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        var url = request.url();
        response = await Dio().get(url);
      } else {
        response = await Dio()
            .post(request.url(), data: request.params, options: option);
      }
    } on DioError catch (e) {
      error = e;
      response = e.response;
    }
    if (error != null) {
      throw LpNetError(response?.statusCode ?? -1, error.toString(), "请求错误");
    }
    return buildRes(response!, request);
  }

  BaseResponse buildRes(Response response, BaseRequest request) {
    if (response.statusCode == 200) {
      var result = response.data;
      var data = result['data'];
      var msg = result['errorMsg'];
      var code = result['errorCode'];
      return BaseResponse(data, code, msg, request);
    }

    return BaseResponse(response.data, response.statusCode ?? -1,
        response.statusMessage, request);
  }
}
